import router from '@/router'
import Validator from '@/utils/Validator'
import emitter from '@/utils/mitt'
import useUserStore from '@/store/modules/user'
import { passRoutes } from '~/env/config'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
NProgress.configure({ showSpinner: false });
router.beforeEach((to, from, next) => {

    const userStore = useUserStore()
    NProgress.start()
    let path = to.path;
    // 如果没有匹配路由
    if (Validator.isEmpty(to?.matched)) {
        next({
            path: '/404'
        })
    } else {
        //传递路由信息
        if (!passRoutes.includes(to.path)) {
            emitter.emit('toRoute', to)
        }
    }
    // 如果已经登录
    if (userStore.isLogin) {
        // 登录态禁止访问路由
        if (path == '/login' || path == '/register') {
            next({
                path: '/'
            })
        }
        // 拥有权限
        if (userStore.hasPermission(to.meta.permission) || userStore.isAdmin) {
            next()
        } else {
            next({
                path: '/403'
            })
        }
    }
    // 未登录 -> 白名单页面可直接进入
    if (!userStore.isLogin && passRoutes.includes(path)) {
        next()
    }
    // 未登录 -> 鉴权页面重定向至 /login
    if (!userStore.isLogin) {
        next({
            path: '/login'
        })
    }
})

router.afterEach(() => {
    NProgress.done()
})
